package com.tender.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.tender.BizMsgAssoUserBizService;
import com.tender.condition.BizMsgAssoUserCondition;
import com.tender.dto.BizMsgAssoUserDTO;
import com.tender.entity.BizMsgAssoUserEntity;
//import com.tender.config.listener.RocketMQProducer;
import com.tender.enums.ErrorTypeEnum;
import com.tender.enums.MsgHasReadEnum;
import com.tender.exceptions.CommonException;
import com.tender.exceptions.WebSocketException;
import com.tender.integration.websocket.service.WebSocketService;
import com.tender.service.BizMsgAssoUserService;
import com.tender.utils.LoginUser;
import com.tender.utils.RedisUtils;
import com.tender.utils.SnowFlakeUtil;
import com.tender.utils.UserProvider;
//import org.apache.rocketmq.client.producer.SendResult;
//import org.apache.rocketmq.client.producer.SendStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

@Slf4j
@Service
public class BizMsgAssoUserBizServiceImpl implements BizMsgAssoUserBizService {

    @Autowired
    private BizMsgAssoUserService bizMsgAssoUserService;
    @Autowired
    private WebSocketService webSocketService;
//    @Autowired
//    private RocketMQProducer rocketMQProducer;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Boolean save(BizMsgAssoUserDTO param) {
        return bizMsgAssoUserService.save(BeanUtil.copyProperties(param, BizMsgAssoUserEntity.class));
    }

    @Override
    public Boolean modify(BizMsgAssoUserDTO param) {
        if (null == param.getMsgId()) {
            throw new CommonException(String.format(ErrorTypeEnum.DATA_NOT_EMPTY.getErrorMsgCn(), "msgId"), ErrorTypeEnum.DATA_NOT_EMPTY.getCode());
        }
        LoginUser userInfo = UserProvider.getUserInfo();
        // 先查询，看是否需要更新为 已读 状态
        BizMsgAssoUserCondition oneParam = new BizMsgAssoUserCondition();
        oneParam.setMsgId(param.getMsgId());
        // 非缓存查询
        BizMsgAssoUserEntity one = bizMsgAssoUserService.selectOne(oneParam, false);

        if (null != one && MsgHasReadEnum.HAS_READ.getCode() == one.getHasRead()) {
            return true;
        }

        // 更新
        BizMsgAssoUserCondition updateParam = new BizMsgAssoUserCondition();
        updateParam.setMsgId(param.getMsgId());
        updateParam.setUserId(userInfo.getUserId());
        updateParam.setHasRead(MsgHasReadEnum.HAS_READ.getCode());  // 已读

        return bizMsgAssoUserService.updateByCondition(updateParam);
    }

    @Override
    public Boolean push(BizMsgAssoUserDTO param) {
        if (null == param.getUserId()) {
            throw new CommonException(String.format(ErrorTypeEnum.DATA_NOT_EMPTY.getErrorMsgCn(), "用户id"), ErrorTypeEnum.DATA_NOT_EMPTY.getCode());
        }
        log.info("【推送消息】userId: {}, param: {}", param.getUserId(), JSON.toJSONString(param));
        Long msgId = Long.parseLong(SnowFlakeUtil.nextId());
        param.setMsgId(msgId);
        param.setId(msgId);
        if (null == param.getTenantId()) {
            param.setTenantId(0L);
        }
        param.setCreateUserId(param.getUserId());
        param.setUpdateUserId(param.getUserId());
        Date now = new Date();
        param.setGmtCreate(now);
        param.setGmtUpdate(now);
        // 推送的消息，首先入 DB
        log.info("【推送消息】userId: {}, 入 db 的参数: {}", param.getUserId(), JSON.toJSONString(param));
        try {
            this.save(param);
        } catch (Exception e) {
            throw new WebSocketException(ErrorTypeEnum.WEB_SOCKET_MSG_SAVE_INFO_EXP);
        }
        log.info("【推送消息】userId: {}, 入 db 成功", param.getUserId());

        // 1、判断用户是否在线
        String applicationName = (String)redisUtils.get(String.valueOf(param.getUserId()));
        // 用户在线
        if (StringUtils.isNotBlank(applicationName)) {
            try {
                webSocketService.sendMessage(String.valueOf(param.getUserId()), param.getDevice(), JSON.toJSONString(param));
                return true;
            } catch (IOException e) {
                // do nothing! 入db 成功了，后期可以补偿消息推送，这边不需要抛异常！
            }
        }

//        Boolean flag = (Boolean)redisUtils.get(Constants.USER_WS_CONNECT_STATUS_KEY + Constants.REDIS_JOIN + param.getUserId());
//        if (null != flag && flag) {
//            // 用户在线
//            SendResult sendResult = rocketMQProducer.setMsg(JSON.toJSONString(param));
//            if (null != sendResult && sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
//                return true;
//            }
//        }

        return false;
    }

}
